import urllib.request
import urllib.parse
import json


def youado(content):
    # 设置路径,需要将 _o 删除
    url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
    # 添加请求头，方式一
    """
    head = {}
    head[
        'User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
    """

    # 新建字典
    data = {}
    # 向字典中添加Form Data
    data['i'] = content
    # data['i'] = 'fuck you'
    data['from'] = 'AUTO'
    data['to'] = 'AUTO'
    data['smartresult'] = 'dict'
    data['client'] = 'fanyideskweb'
    # data['salt'] = '1541753761914'
    data['salt'] = '1541755760244'
    # data['sign'] = '6b5df0b421e1668ef0ef5ba7327c2ac9'
    data['sign'] = '161e268b2b02813dc8a688f0bbb491f1'
    data['doctype'] = 'json'
    data['version'] = '2.1'
    data['keyfrom'] = 'fanyi.web'
    data['action'] = 'FY_BY_REALTIME'
    data['typoResult'] = 'false'

    # 设置编码
    data = urllib.parse.urlencode(data).encode('utf-8')

    # req = urllib.request.Request(url,data,head)
    req = urllib.request.Request(url, data)
    # 添加请求头，方式二
    req.add_header('User-Agent',
                   'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36')

    response = urllib.request.urlopen(req)
    html = response.read().decode('utf-8')
    # print(req.headers)
    # print(html)

    target = json.loads(html)['translateResult'][0][0]['tgt']
    return target


print('提示:输入 quit! 退出')

while True:
    content = input('请输入需要翻译的内容:')
    if content == 'quit!':
        break
    print('翻译结果如下: %s' % youado(content))
    print('-----------------------')
